﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebApi_JWT.Model;
namespace WebApi_JWT.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthorizeController:ControllerBase
    {
        private JwtSeting _jwtSetting;

        public AuthorizeController(IOptions<JwtSeting> _jwtSettingsAccesser)
        {
            _jwtSetting = _jwtSettingsAccesser.Value;
        }
        [HttpPost]
        [Route("token")]
        public IActionResult Token([FromBody]LoginViewModel viewModel)
        {
            if(!(viewModel.User=="ztb"&&viewModel.Password=="123456"))
            {
                return BadRequest();
            }
            var claim = new Claim[]   //添加自定义信息
            {
                new Claim(ClaimTypes.Name,"ztb"),
                new Claim(ClaimTypes.Role,"admin")
            };
            //对称密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecreKey));
            //签名证书（密钥，加密算法）
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成token 
            var token = new JwtSecurityToken(_jwtSetting.Issuer, _jwtSetting.Audience, claim, DateTime.Now, DateTime.Now.AddMinutes(30),creds);
            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
        }
    }
}
